package com.emath.activities;

import java.io.IOException;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager.LayoutParams;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lnl.R;
import com.emath.objects.CurrentCard;
import com.emath.objects.Player;
import com.emath.shared.BigRational;
import com.emath.shared.Globals;

public class FractionInput extends Activity {
	BigRational totalSum;
	EditText fractionEditText1;
	private void recyclebitmap(ImageView img) {
		ImageView myimg = img;
		Drawable drawable;
		drawable = img.getDrawable();
		if (drawable instanceof BitmapDrawable) {
			BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
			if (null != bitmapDrawable
					&& !bitmapDrawable.getBitmap().isRecycled()) {
				bitmapDrawable.getBitmap().recycle();
			} else {

				Log.e("recycled", "bitmap is already recycled");
			}
			bitmapDrawable = null;

		}
	}
	public BitmapDrawable writeOnDrawable(int drawableId, CurrentCard card,
			int cardID) throws IOException {

		int drawableid = 0;
		int size;
		final float scale = getResources().getDisplayMetrics().density;

		if (card.getCardType().equals("Resource"))
			drawableid = getResources().getIdentifier("sample_2", "drawable",
					getPackageName());
		if (card.getType1().equals("Student"))
			drawableid = getResources().getIdentifier("sample_0", "drawable",
					getPackageName());
		if (card.getType1().equals("Leader"))
			drawableid = getResources().getIdentifier("sample_1", "drawable",
					getPackageName());
		if (card.getType1().equals("Artist"))
			drawableid = getResources().getIdentifier("sample_3", "drawable",
					getPackageName());
		if (card.getType1().equals("Athlete"))
			drawableid = getResources().getIdentifier("sample_4", "drawable",
					getPackageName());
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inPurgeable = true;
		MemoryInfo mi = new MemoryInfo();
		ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
		activityManager.getMemoryInfo(mi);
		long availableMegs = mi.availMem / 1048576L;
		Log.e("memory", String.valueOf(availableMegs));
		Bitmap original = BitmapFactory.decodeResource(getResources(),
				drawableid, options);
		// int si=sizeOf(original);
		// Log.e("memory",String.valueOf(si));
		// logHeap();
		Bitmap bm = original.copy(Bitmap.Config.RGB_565, true);
		// int si2=sizeOf(bm);
		// Log.e("memory",String.valueOf(si2));
		original.recycle();

		Paint paint = new Paint();
		paint.setStyle(Style.FILL);
		paint.setColor(Color.BLACK);

		size = (int) (33.33 * scale + 0.5f);
		paint.setTextSize(size);

		Paint paint2 = new Paint();// for drawing the levelups
		paint2.setStyle(Style.FILL);
		paint2.setColor(Color.BLACK);
		size = (int) (16.66 * scale + 0.5f);
		paint2.setTextSize(size);

		Canvas canvas = new Canvas(bm);
		String mind = "M " + String.valueOf(card.getMind());
		String strength = "S " + String.valueOf(card.getStrength());
		String charm = "C " + String.valueOf(card.getCharm());
		String type = "";
		String name = card.name;

		if (!card.type1.equals(""))
			type = type + card.type1 + " ";
		if (!card.type2.equals(""))
			type = type + card.type2 + " ";
		if (!card.type3.equals(""))
			type = type + card.type3 + " ";

		String cost = card.cost;
		String levelups = "";
		for (int i = 0; i < 3; i++) {
			switch (i) {
			case 0:
				if (!card.levelup1.equals(""))
					levelups = levelups + card.levelup1 + " ";
				break;
			case 1:
				if (!card.levelup2.equals(""))
					levelups = levelups + card.levelup2 + " ";
				break;
			case 3:
				if (!card.levelup3.equals(""))
					levelups = levelups + card.levelup3 + " ";
				break;
			}

		}

		Paint paint3 = new Paint(); // for drawing the levelups
		paint3.setStyle(Style.FILL);
		paint3.setColor(Color.BLACK);
		size = (int) (10 * scale + 0.5f);
		paint3.setTextSize(size);

		canvas.drawText(cost, (float) (.057 * bm.getWidth()),
				(bm.getHeight() / 2), paint);
		canvas.drawText(type, (float) (.057 * bm.getWidth()),
				(float) (.933 * bm.getHeight()), paint3);

		canvas.drawText(mind, (float) (.057 * bm.getWidth()),
				(float) ((bm.getHeight() / 2) - (.363 * bm.getHeight())), paint);
		canvas.drawText(charm, (float) (.4022 * bm.getWidth()),
				(float) ((bm.getHeight() / 2) - (.363 * bm.getHeight())), paint);
		canvas.drawText(strength, (float) (.7327 * bm.getWidth()),
				(float) ((bm.getHeight() / 2) - (.363 * bm.getHeight())), paint);
		canvas.rotate(90, bm.getWidth() / 2, bm.getHeight() / 2);
		canvas.drawText(levelups, (float) (.0718 * bm.getWidth()) + 5,
				(float) ((bm.getHeight() / 2) - (.339 * bm.getHeight())) + 15,
				paint3);
		canvas.rotate(270, bm.getWidth() / 2, bm.getHeight() / 2);
		float x = (float) (.905 * bm.getWidth());
		size = (int) (13.33 * scale + 0.5f);
		paint3.setTextSize(size);
		size = (int) (6.66 * scale + 0.5f);

		if (!card.cardType.equals("Resource")) {
			for (int i = 0; i < Integer.parseInt(card.level); i++) {
				canvas.drawCircle(x, (float) (.932 * (bm.getHeight())), size,
						paint3);
				x = (float) (x - (.07184 * bm.getWidth()));
			}
		}
		int width = (int) (120 * scale + 0.5f);
		int height = (int) (133.33 * scale + 0.5f);
		DisplayMetrics metrics = getResources().getDisplayMetrics();

		Bitmap image = Bitmap.createScaledBitmap((Globals.libraryObj
				.getCardbyID(String.valueOf(card.getCardID()))).getBitmap(),
				width, height, false);

		canvas.drawBitmap(image, (float) (.259 * bm.getWidth()),
				(float) (.157 * bm.getHeight()), paint2);
		canvas.drawText(name, (float) (.0575 * bm.getWidth()),
				(float) (.884 * bm.getHeight()), paint2);

		return new BitmapDrawable(getApplicationContext().getResources(), bm);
	}

	public static String toFraction(double d, int factor) {
		if (d == 0.0)
			return "0";
		StringBuilder sb = new StringBuilder();
		if (d < 0) {
			sb.append('-');
			d = -d;
		}

		long l = (long) d;
		if (l != 0)
			sb.append(l);
		d -= l;

		double error = Math.abs(d);
		int bestDenominator = 1;
		for (int i = 2; i <= factor; i++) {
			double error2 = Math.abs(d - (double) Math.round(d * i) / i);
			if (error2 < error) {
				error = error2;
				bestDenominator = i;
			}
		}
		if (bestDenominator > 1)
			sb.append(' ').append(Math.round(d * bestDenominator)).append('/')
					.append(bestDenominator);
		return sb.toString();
	}

	public BigRational addFraction(BigRational num, BigRational fraction) {
		int numerator = fraction.getNumerator().intValue();
		int denominator = fraction.getDenominator().intValue();
		if (num.isInteger()) {
			numerator = numerator + (denominator * num.intValue());
			num = BigRational.getInstance(numerator, denominator);
		} else {
			num = num.add(fraction);
		}
		return num;
	}

	public BigRational subtractFraction(BigRational num, BigRational fraction) {
		int numerator = fraction.getNumerator().intValue();
		int denominator = fraction.getDenominator().intValue();
		if (num.isInteger()) {
			numerator = (denominator * num.intValue()) - numerator;
			num = BigRational.getInstance(numerator, denominator);
		} else {
			num = num.subtract(fraction);
		}

		if (num.floatValue() <= 0)
			num = BigRational.valueOf("0");

		return num;
	}

	public void onClickAddFraction1(View view) {
		totalSum = addFraction(totalSum, BigRational.getInstance(1, 4));
		fractionEditText1.setText(toFraction(totalSum.doubleValue(), 1000));
	}

	public void onClickAddFraction2(View view) {
		totalSum = addFraction(totalSum, BigRational.getInstance(1, 3));
		fractionEditText1.setText(toFraction(totalSum.doubleValue(), 1000));
	}

	public void onClickAddFraction3(View view) {
		totalSum = addFraction(totalSum, BigRational.getInstance(1, 2));
		fractionEditText1.setText(toFraction(totalSum.doubleValue(), 1000));
	}

	public void onClickSubtractFraction1(View view) {
		totalSum = subtractFraction(totalSum, BigRational.getInstance(1, 4));
		fractionEditText1.setText(toFraction(totalSum.doubleValue(), 1000));
	}

	public void onClickSubtractFraction2(View view) {
		totalSum = subtractFraction(totalSum, BigRational.getInstance(1, 3));
		fractionEditText1.setText(toFraction(totalSum.doubleValue(), 1000));
	}

	public void onClickSubtractFraction3(View view) {
		totalSum = subtractFraction(totalSum, BigRational.getInstance(1, 2));
		fractionEditText1.setText(toFraction(totalSum.doubleValue(), 1000));
	}

	public void onClickClear(View view) {
		totalSum = BigRational.valueOf("0");
		fractionEditText1.setText("0");
	}

	public void onClickSubmit(View view) {
		if (totalSum.compareTo(Player.currentcard.getPower()) == 0) {
			Player.correct = true;
			Toast.makeText(this, "Correct!", Toast.LENGTH_SHORT).show();

		} else {
			Toast.makeText(this, "Incorrect!", Toast.LENGTH_SHORT).show();
			Player.correct = false;
		}
		Player.finished = true;

		finish();
		// Store in global?
	}

	public class MyCount extends CountDownTimer {
		public MyCount(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
		}
		@Override
		public void onFinish() {
			// TextView timer = (TextView) findViewById(R.id.Timer);
			// the timer keeps going after onClickSubmit
			// so I put this if statement to prevent the Toast from
			// appearing later on

			Player.finished = true;
			Player.correct = false;
			finish();
		}
		@Override
		public void onTick(long millisUntilFinished) {
			if (Player.finished)
				return;
			TextView timer = (TextView) findViewById(R.id.Timer);
			// this will be called every second
			timer.setText("Remaining: " + millisUntilFinished / 1000);
		}

	}
	public class Timer extends AsyncTask<Context, Void, Context> {

		@Override
		protected Context doInBackground(Context... Contexts) {

			// added for the timer settings
			/*
			 * int timeAllowed = 45000;// 45 second default if
			 * (Globals.settingsHolder[3] == 0) // Easy Difficulty { timeAllowed
			 * = 45000;// 45 seconds on easy } else if
			 * (Globals.settingsHolder[3] == 1) // Medium Difficulty {
			 * timeAllowed = 20000;// 20 seconds on medium } else if
			 * (Globals.settingsHolder[3] == 2) // Hard Difficulty { timeAllowed
			 * = 15000;// 15 seconds on hard mode }
			 * 
			 * MyCount counter = new MyCount(timeAllowed, 1000);
			 * counter.start();
			 */
			return Contexts[0];
		}

		@Override
		protected void onPostExecute(Context result) {
			// if (!Player.finished)
			// Toast.makeText(FractionInput.this,
			// "Time Up!",Toast.LENGTH_SHORT).show();
			super.onPostExecute(result);
		}

	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fraction_widget);
		getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON);

		// added for the timer settings
		int timeAllowed = 45000;// 45 second default
		if (Globals.settingsHolder[3] == 0) // Easy Difficulty
		{
			timeAllowed = 45000;// 45 seconds on easy
		} else if (Globals.settingsHolder[3] == 1) // Medium Difficulty
		{
			timeAllowed = 20000;// 20 seconds on medium
		} else if (Globals.settingsHolder[3] == 2) // Hard Difficulty
		{
			timeAllowed = 15000;// 15 seconds on hard mode
		}

		MyCount counter = new MyCount(timeAllowed, 1000);
		counter.start();
		new Timer().execute(getApplicationContext());
		// end of timer setup for onCreate

		totalSum = BigRational.valueOf("0");
		fractionEditText1 = (EditText) findViewById(R.id.FractionEditText1);
		TextView function = (TextView) findViewById(R.id.TextViewFunction);
		TextView difficulty = (TextView) findViewById(R.id.TextViewDifficulty);

		// Display the function
		String cardType = Player.currentcard.type1;
		if (cardType.equalsIgnoreCase("Athlete")) {
			function.setText("(1/4)Mind + (1/4)Charm + (1/2)Strength");
		} else if (cardType.equalsIgnoreCase("Artist")) {
			function.setText("(1/4)Mind + (1/2)Charm + (1/4)Strength");
		} else if (cardType.equalsIgnoreCase("Student")) {
			function.setText("(1/2)Mind + (1/4)Charm + (1/4)Strength");
		} else if (cardType.equalsIgnoreCase("Leader")) {
			function.setText("(1/3)Mind + (1/3)Charm + (1/3)Strength");
		}

		// Display the difficulty
		if (Globals.settingsHolder[3] == 0) {
			difficulty.setText("Difficulty: Easy");
		} else if (Globals.settingsHolder[3] == 1) {
			difficulty.setText("Difficulty: Medium");
		} else if (Globals.settingsHolder[3] == 2) {
			difficulty.setText("Difficulty: Hard");
		}

		int id = getResources().getIdentifier("sample_0", "drawable",
				getPackageName());
		ImageView image = (ImageView) findViewById(R.id.IVCard1);

		recyclebitmap(image);
	try {
		image.setImageDrawable(writeOnDrawable(id, Player.currentcard,
					Player.currentcard.cardID));
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

	}

	@Override
	public void onBackPressed() {
	}

	@Override
	protected void onPostResume() {
		if (Globals.focusedActivity.equals("FractionInput")) {
			if (Globals.settingsHolder[1] == 1) {
				startService(Globals.backgroundMusicService);
			}
			Globals.isMusicPlaying = true;
		}
		super.onPostResume();
	}

	@Override
	protected void onPause() {
		if (this.isFinishing()) {
			Globals.focusedActivity = "GamePlay";
		} else {
			if (Globals.settingsHolder[1] == 1) {
				stopService(Globals.backgroundMusicService);
			}
			Globals.isMusicPlaying = false;
		}
		super.onPause();
	}
}